package com.ibr.ticketmanagement.app.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.ibr.ticketmanagement.app.data.ActionPlan;
import com.ibr.ticketmanagement.app.data.FEReport;
import com.ibr.ticketmanagement.app.data.Location;
import com.ibr.ticketmanagement.app.data.LocationPart;
import com.ibr.ticketmanagement.app.data.Part;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Girishn on 08-05-2014.
 */
public class Utility {

    // Splash screen timer
    public static final int SPLASH_TIME_OUT = 3000;
    public static final String APP_SOARLOGIC_FIX = "1100990011";
    public static final String PREFS_NAME = "IBR_PPrefsStorage";
    public static final String PREFS_VARIABLE_TOKEN = "token";
    public static final String PREFS_VARIABLE_LOCATION_PART_VERSION = "location_part_version";
    public static final String GET_SALT_FOR_USER_URL = "http://support.ib-r.com.au/api/users/%s/user.json";
    public static final String FETCH_ACTION_PlAN_URL = "http://support.ib-r.com.au/api/actions/%s/plan/index.json";
    public static final String FETCH_PARTS_URL = "http://support.ib-r.com.au/api/parts/index.json";
    public static final String FETCH_LOCATIONS_URL = "http://support.ib-r.com.au/api/locations/index.json";
    public static final String POST_FE_REPORT_URL = "http://support.ib-r.com.au/api/reports/creates.json";
    private static final String DEBUG_TAG = "Utility";
    private static final String LOGIN_URL = "http://support.ib-r.com.au/api/user/me";
    private static final String PREFS_VARIABLE_USERNAME = "PREFS_VARIABLE_USERNAME";
    private static final String PREFS_VARIABLE_PASSWORD = "PREFS_VARIABLE_PASSWORD";
    private static final String PREFS_VARIABLE_SALT = "PREFS_VARIABLE_SALT";
    private static final String PREFS_VARIABLE_USER_ID = "PREFS_VARIABLE_USER_ID";
    private static final String PREFS_VARIABLE_LOGIN_RESPONSE = "PREFS_VARIABLE_LOGIN_RESPONSE";
    private static final String PREFS_VARIABLE_FE_ENGINEER_ID = "PREFS_VARIABLE_FE_ENGINEER_ID";
    private static final String TAG = "UTILITY";
    private static final String PREFS_VARIABLE_BACKGROUND_SERVICE_RAN = "PREFS_VARIABLE_BACKGROUND_SERVICE_RAN";
    private static final String PREFS_VARIABLE_LOCATIONS_ARRAY = "PREFS_VARIABLE_LOCATIONS_ARRAY";
    private static final String PREFS_VARIABLE_PARTS_ARRAY = "PREFS_VARIABLE_PARTS_ARRAY";
    private static final String PREFS_VARIABLE_INITIALIZE_DB = "PREFS_VARIABLE_INITIALIZE_DB";
    public static String USER_AGENT = System.getProperty("http.agent");
    private static String[] location = {"Select Location", "Syd1", "Adl1", "Syd2", "Melb1", "IBRSyd", "IBRMelb", "Kor", "SST1", "Maintech"};
    private static String[] part = {"Select Part", "507284-001", "512744-001", "504334-001", "501536-001", "462976-001", "398648-001", "49Y1436", "42D0677", "42D0641", "68Y8186", "49Y1445", "307132-001", "378915-001", "432321-001", "416473-001", "418399-001", "289041-001", "289243-001", "289044-001", "496069-001", "403781-001", "432668-001", "X1562", "43W4342", "39Y7236", "501534-001", "508010-001", "432671-001", "42D0633", "283551-B21", "431954-003", "286712-004", "300955-014", "177988-001", "286712-006", "286716-B22", "404708-001", "404670-002", "365695-008", "360209-003", "365699-001", "360209-010", "274779-001", "373030-051", "416107-001", "39Y7235", "39Y7263", "39Y7225", "379123-001", "380622-001", "399771-001", "432670-001", "398708-061", "504015-002", "418367-B21", "459512-002", "42D0632", "42D0636", "421D0638", "42D0678", "42D0681", "431930-002", "9MB066-033", "416472-001", "405476-051", "405478-071", "408855-B21", "375861-B21", "376597-001", "46C9040", "81Y4451", "462969-B21", "460499-001", "49Y1446", "47J0157", "49Y1435", "47J0156", "500203-051", "500205-071", "500658-B21", "500203-061", "504062-B21", "507127-B21", "507129-004", "512547-B21", "507618-004", "507616-B21", "499250-101", "536404-001", "512547-B21", "UD558", "HYMP512R724-E3", "500662-B21", "42D0638", "42D0637", "373030-851", "289241-001", "507283-001", "507283-001", "CM318", "501158-001", "123482-005", "X1563", "G3399", "405835-001", "012765-000", "42D0500", "42D0496", "42d0494", "42D0495", "432320-001", "431958-B21", "504015-002", "501535-001", "375863-012", "462975-001", "462967-B21", "49Y1437", "49Y1415", "47J0136", "49Y1397", "X3R5M", "CM318", "XM371", "TK238", "HT952", "UP937", "ST973402SS", "404714-001", "42D554", "416106-001", "378914-001", "359242-001", "345113-051", "69Y5082", "00D3284", "46M0829", "46M0851", "44E8825", "43W4339", "44X1945", "49Y4237", "46M6067", "46M6065", "QMI2572", "49Y1441", "47J0152", "49Y1431", "46C7451", "43X5318", "44X1948", "43W4341", "43W4339", "289544-001", "279036-001", "69Y5062", "69Y5063", "69Y4324", "69Y2328", "60Y0329", "81Y6625", "43V7070", "U8735", "NU209", "XJ547", "X8483", "314670-001", "501157-001", "X1560", "4D554", "M393T3253FZ0", "G3399", "CG535", "44E8763", "511778-001", "49Y1425", "81Y9993", "94Y6670", "606020-001", "HC486", "UM142", "NP659", "MY412", "9M912", "J4717", "FC960", "X150K", "HT953", "A0751669", "N4332", "8K146", "XT764", "X1564", "364622-B23", "496066-001", "430449-001", "300702-001", "300700-001", "300699-001", "359241-001", "441830-001", "338022-001", "347884-001", "359773-001", "406421-001", "289561-001", "383337-001", "374552-001", "36P3337", "430450-001", "361392-001", "361390-001", "361399-001", "488138-001", "373029-851", "260740-001", "AA979A", "407747-001", "501533-001", "305443-001", "447029-001", "394035-001", "375696-002", "405831-001", "405836-001", "361316-010", "398706-051", "394038-001", "416799-001", "408788-001", "416799-001", "404701-001", "347779-001", "289042-001", "351126-001", "408791-001", "408792-001", "412736-001", "391137-001", "407749-001", "337867-501", "364517-001", "294766-9D4", "405832-001", "419619-001", "419621-001", "407748-001", "373537-001", "419898-001", "419903-001", "378912-001", "373028-051", "177986-001", "413486-001", "249106-001", "267132-001", "313559-001", "356784-001", "359771-001", "359774-001", "289563-001", "314933-FD1", "416471-001", "401026-001", "260741-001", "262695-005", "364622R-B22", "484425-001", "508955-001", "531228-001", "531221-001", "531223-001", "531225-001", "493083-001", "373029-051", "411248-001", "194989-002", "321632-501", "233303-001", "407750-001", "266655-001", "284848-001", "222837-001", "454274-001", "289552-001", "228507-001", "228504-001", "309629-001", "279160-001", "381819-001", "175918-042", "312257-001", "192201-001", "336439-001", "177726-001", "125425-001", "317465-001", "161105-001", "587224-001", "212398-005", "212192-001", "457877-001", "351518-001", "384377-061", "409124-001", "261585-041", "587324-001", "462919-001", "581311-001", "599038-001", "578882-001", "254786-B21", "416357-001", "500172-B21", "501535-001", "289553-001", "90P1316", "12R6304", "12R6302", "12R8143", "24P8174", "40K6246", "39Y7351", "44X5299", "43X0825", "53P0262", "00N7227", "09N9447", "00N8953", "33L3128", "09N9909", "33L3126", "37L6782", "38L3240", "37L0315", "09N0883", "44T1586", "44X1947", "53P1223", "42D0652", "90P1383", "43W4297", "43W4342-C", "39Y7364", "39Y7409", "69Y0650", "46M0997", "46M6498", "69Y1332", "69Y0649", "81Y9990", "?", "418398-001", "397739-001", "43W7510", "LPE11000", "42D0421", "42D0422", "9F6066-039", "412320-001", "228508-001", "407621-001", "42D0628", "395910-001", "504062-B21", "42D0627", "42D0631", "90Y8878", "90Y8881", "49Y2004", "90Y8872", "90Y8873", "90Y8876", "581311-001", "581286-B21", "94Y8071", "94Y8079", "94Y8078", "634025-001", "39Y7355", "593722-B21", "593743-001", "405914-001", "289554-001", "0N4867", "0T4363", "2850 Raid Kit", "4M685", "9U175", "A4218", "F4615", "H1813", "H6675", "RC22O", "U1931", "U8373", "X5535", "CA06227-B60700DU", "CA21334-B76X", "07N8818", "012585-501", "012588-001", "0950-3245", "0950-3316", "0950-3470", "0950-3471", "0950-3794", "0950-3819", "0950-4173", "0950-4352", "0950-4462", "0950-4515", "0950-4526", "192147-002", "226949-231", "226949-320", "228503-001", "231128-001", "261584-041", "266240-001", "266284-001", "271837-008", "283033-001", "286774-004", "286778-B22", "078-000-062", "306641-003", "307103-001", "314669-001", "321520-001", "321633-002", "335774-001", "337273-001", "356782-001", "356783-001", "359253-001", "365695-001", "365695-007", "366300-001", "CX-4G10-600", "7212", "501536-001", "03R120", "0T4363", "432671-001", "434916-001", "504334-001", "512744-001", "XT764", "501535-001", "504062-B21", "507283-001", "512547-B21", "100-562-144", "100-562-144", "078-000-083", "071-000-462", "100-561-803", "071-000-410", "071-000-462", "CX-4G15-73", "071-000-410", "CX-4g10-300", "CX-4G15-73", "CX-4G10-300", "653954-001", "419616-001", "038-003-085", "CR2032", "69y5787", "592261-001", "507284-001"};
    private static String token = "";

    public static String[] getPart(Context context) {
        SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
        return stringToArray(settings.getString(PREFS_VARIABLE_PARTS_ARRAY, "part"));
    }

    public static void setPart(Context context, String[] part) {
        Utility.part = part;
        SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(PREFS_VARIABLE_PARTS_ARRAY, arrayToString(Utility.part));
        // Commit the edits!
        editor.commit();
    }

    public static String[] getLocation(Context context) {
        SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
        return stringToArray(settings.getString(PREFS_VARIABLE_LOCATIONS_ARRAY, "location"));
    }

    private static String[] stringToArray(String arrayString) {
        if ("location".equals(arrayString)) {
            return Utility.location;
        }
        if ("part".equals(arrayString)) {
            return Utility.part;
        }
        return arrayString.split(",");
    }

    public static void setLocation(Context context, String[] location) {
        Utility.location = location;
        SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(PREFS_VARIABLE_LOCATIONS_ARRAY, arrayToString(Utility.location));
        // Commit the edits!
        editor.commit();
    }

    private static String arrayToString(String[] array) {
        StringBuffer sb = new StringBuffer("");
        for (int i = 0; i < array.length; i++) {
            if (i > 0) sb.append(",");
            sb.append(array[i]);
        }
        return sb.toString();
    }

    public static void setToken(String token) {
        Utility.token = token;
    }

    public static boolean isLoggedIn(Context context) {
        if (token == null || "".equals(token)) {
            SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
            setToken(settings.getString(PREFS_VARIABLE_TOKEN, ""));
        }
        return (null != token && !"".equals(token));
    }

    public static void setLoginToken(Context context, String token) {
        SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(PREFS_VARIABLE_TOKEN, token);

        // Commit the edits!
        editor.commit();

        //Set in variable
        isLoggedIn(context);
    }

    public static long setLocationVersion(Context context, long version) {
        SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putLong(PREFS_VARIABLE_LOCATION_PART_VERSION, version);
        // Commit the edits!
        editor.commit();
        return version;
    }

    public static void getActionPlans(Context context) {
        //check the network available
        ConnectivityManager connMgr = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {
            JSONObject jsonActionPlans = Utility.downloadJsonFromURI(String.format(Utility.FETCH_ACTION_PlAN_URL,
                    (new String[]{String.valueOf(Utility.getfeEngineerId(context))})), true);
            saveActionPlan(createActionPlans(jsonActionPlans), context);
        } else {
            Toast.makeText(context,
                    "No network connection available. Please check your Network Connection.", Toast.LENGTH_LONG)
                    .show();
        }
    }

    private static void saveActionPlan(List<ActionPlan> actionPlans, Context context) {
        if (actionPlans != null && !actionPlans.isEmpty()) {
            DatabaseHandler db = new DatabaseHandler(context);
            for (ActionPlan ap : actionPlans) {
                try {
                    db.addActionPlan(ap);
                } catch (Exception e) {
                    Log.e("Utility", "There was an Exception while adding action plan into the database", e.fillInStackTrace());
                }
            }
        }
    }

    private static List<ActionPlan> createActionPlans(JSONObject jsonActionPlans) {
        List<ActionPlan> actionPlanL = null;
        try {
            JSONArray jArr = jsonActionPlans.getJSONArray("wrapper");
            for (int i = 0; i < jArr.length(); i++) {
                try {
                    JSONObject actionPlanObj = jArr.getJSONObject(i);
                    long ap_order = System.currentTimeMillis();
                    System.out.println("ap_order:" + ap_order);
                    boolean fe_report_created = false;
                    ActionPlan ap = new ActionPlan(actionPlanObj.getInt("ticket"), actionPlanObj.getInt("id"), actionPlanObj.getString("name"), actionPlanObj.getString("work_window_start"),
                            actionPlanObj.getString("action_plan"), actionPlanObj.getString("site_contact_name"),
                            actionPlanObj.getString("site_access"), fe_report_created, ap_order);
                    if (ap != null) {
                        if (actionPlanL == null)
                            actionPlanL = new ArrayList<ActionPlan>();
                        actionPlanL.add(ap);
                    }
                } catch (Exception e) {
                    Log.e("UTILITY", "Parsing Action plan failed.", e.fillInStackTrace());
                }
            }

        } catch (Exception e) {
            Log.e("UTILITY", "There is an Exception while parsing the action plans", e.fillInStackTrace());
        }
        return actionPlanL;
    }


    @Deprecated
    public static String getURL(int type) {
        switch (type) {
            case 0://ACTION.FETCH_ACTION_PlAN
                return "http://support.ib-r.com.au/api/actions/%s/plan/index.json";
            default:
                return null;
        }
    }

    @Deprecated
    public static String getPostParams(int type) {
        switch (type) {
            case 0://ACTION.FETCH_ACTION_PlAN
                return "";
            default:
                return null;
        }
    }

    // Given a URL, establishes an HttpUrlConnection and retrieves
    // the web page content as a InputStream, which it returns as
    // a string.
    private static String downloadUrl(String myurl, String urlParameters) throws IOException {
        if (myurl == null || "".equals(myurl)) return null;
        BufferedReader in = null;

        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("User-Agent", USER_AGENT);
            conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

            // Send post request
            conn.setDoOutput(true);
            if (urlParameters != null && !"".equals(urlParameters)) {
                DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(urlParameters);
                wr.flush();
                wr.close();
            } else {
                // Starts the query; Not required when using DataOutputStream
                conn.connect();
            }
            int response = conn.getResponseCode();
            Log.d(DEBUG_TAG, "Sending 'POST' request to URL :" + myurl);
            Log.d(DEBUG_TAG, "The url parameters are: " + urlParameters);
            Log.d(DEBUG_TAG, "The response is: " + response);

            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));

            // Convert the InputStream into a string
            return readResponse(in);

            // Makes sure that the InputStream is closed after the app is
            // finished using it.
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }

    // Reads an InputStream and converts it to a String.
    public static String readResponse(BufferedReader in) throws IOException, UnsupportedEncodingException {
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        return response.toString();
    }

    public static ActionPlan getLatestActionPlan(Context context) {
        DatabaseHandler db = new DatabaseHandler(context);
        return db.getLatestActionPlan();
    }

    public static JSONObject downloadJsonFromURI(String url, boolean isArray) {
        JsonParser jsonParser = new JsonParser();
        String json = jsonParser
                .getJSONFromUrl(url);

        Log.e("Response: ", "> " + json);

        if (json != null) {
            try {
                JSONObject jObj = null;
                if (!isArray) {
                    jObj = new JSONObject(json);
                } else {
                    JSONArray jsonArray = new JSONArray(json);
                    jObj = new JSONObject();
                    jObj.put("wrapper", jsonArray);
                }
                return jObj;
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

    public static long saveLocation(Context context, Location location) {
        DatabaseHandler db = new DatabaseHandler(context);
        Log.i(TAG, "Checking if an old location is available in DB.");
        Location oldLocation = db.getLocation(location);
        Log.i(TAG, "Got an old location from DB. Need to check if correct.");
        if (oldLocation == null || oldLocation.get_id() <= 0) {
            Log.i(TAG, "Old location is not available");
            location = db.saveLocation(location);
            Log.i(TAG, "Saving a new location");
        } else {
            //update the version for the earlier location in DB
            Log.i(TAG, "Updating version in old location");
            oldLocation.setVersion(location.getVersion());
            location = db.updateLocation(oldLocation);
            Log.i(TAG, "Updating an old location");
        }
        return location.get_id();
    }

    public static long savePart(Context context, Part part, long locId, int quantity) {
        DatabaseHandler db = new DatabaseHandler(context);
        Log.i(TAG, "Checking if an old part is available in DB.");
        Part oldPart = db.getPart(part);
        Log.i(TAG, "Got an old part from DB. Need to check if correct.");
        if (oldPart.get_id() <= 0) {
            Log.i(TAG, "Old part is not available");
            part = db.savePart(part);
            Log.i(TAG, "Saving a new part");
        } else {
            Log.i(TAG, "Part already available in DB.");
            part = oldPart;
        }
        if (locId > 0) {
            Log.i(TAG, "Will create a location part object");
            LocationPart locationPart = new LocationPart(locId, part.get_id(), quantity);
            Log.i(TAG, "location part object created. Will save in DB");
            db.saveLocationPart(locationPart);
            Log.i(TAG, "location part object saved in DB");
        } else {
            Log.i(TAG, "Location id is not correct. Location Part objec will not be created");
        }
        return part.get_id();
    }

    public static long getNextLocationVersion(Context context) {
        long nextVersion = getLocationVersion(context);
        if (-1L == nextVersion) {
            setLocationVersion(context, ++nextVersion);
        } else if ((Long.MAX_VALUE - 1) <= nextVersion) {
            nextVersion = 0;
            setLocationVersion(context, nextVersion);
        }
        return nextVersion;
    }

    public static long getLocationVersion(Context context) {
        SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
        return settings.getLong(PREFS_VARIABLE_LOCATION_PART_VERSION, -1L);
    }

    public static String doLogin(String mEmail, String mPassword, String salt) throws IOException {
        BufferedReader in = null;
        String myurl = Utility.LOGIN_URL;
        InputStream is = null;
        try {
            Log.d(DEBUG_TAG, "Sending 'GET' request to URL :" + myurl);
            //here you use the WsseToken class to get wsse headers
            WsseToken token = new WsseToken(mEmail, mPassword, salt);
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.setRequestProperty(WsseToken.HEADER_AUTHORIZATION, token.getAuthorizationHeader());
            conn.setRequestProperty(WsseToken.HEADER_WSSE, token.getWsseHeader());
            conn.setRequestProperty("User-Agent", USER_AGENT);
            conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
            conn.connect();
            int response = conn.getResponseCode();
            Log.d(DEBUG_TAG, "Sending 'GET' request to URL :" + myurl);
            Log.d(DEBUG_TAG, "The response is: " + response);
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            // Convert the InputStream into a string
            return readResponse(in);
            // Makes sure that the InputStream is closed after the app is
            // finished using it.
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }

    public static String getUserName(Context context) {
        SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
        return settings.getString(PREFS_VARIABLE_USERNAME, "");
    }

    public static String getUserPassword(Context context) {
        SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
        return settings.getString(PREFS_VARIABLE_PASSWORD, "");
    }

    public static String getUserSalt(Context context) {
        SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
        return settings.getString(PREFS_VARIABLE_SALT, "");
    }

    public static void setUser(Context context, String mEmail, String mPassword, String salt, int userId, int feEngineerId) {
        SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(PREFS_VARIABLE_USERNAME, mEmail);
        editor.putString(PREFS_VARIABLE_PASSWORD, mPassword);
        editor.putString(PREFS_VARIABLE_SALT, salt);
        editor.putInt(PREFS_VARIABLE_USER_ID, userId);
        editor.putInt(PREFS_VARIABLE_FE_ENGINEER_ID, feEngineerId);
        // Commit the edits!
        editor.commit();
    }

    public static int getUserId(Context context) {
        SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
        return settings.getInt(PREFS_VARIABLE_USER_ID, 0);
    }

    public static void saveFEReport(Context context, FEReport feReport) {
        DatabaseHandler db = new DatabaseHandler(context);
        db.addFEReport(feReport);
    }

    public static void setActionPlanFEReportCreated(Context context, int actionPlan_id) {
        DatabaseHandler db = new DatabaseHandler(context);
        ActionPlan ap = db.getActionPlan(actionPlan_id);
        ap.setFe_report_created(true);
        db.updateActionPlan(ap);
    }

    public static int getfeEngineerId(Context context) {
        SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
        return settings.getInt(PREFS_VARIABLE_FE_ENGINEER_ID, 0);
    }

    public static int getfeEngineerId(String response) throws JSONException {
        JSONObject loginResponse = new JSONObject(response);
        try {
            JSONObject field_engineer = loginResponse.getJSONObject("field_engineer");
            return field_engineer.getInt("id");
        } catch (JSONException e) {
            Log.e("LOGINACTIVITY", "Could not get FE id not successful. {JSONException}", e.fillInStackTrace());
        }
        return 0;
    }

    public static void setUserLoginResponse(Context context, String response) {
        SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(PREFS_VARIABLE_LOGIN_RESPONSE, response);

        // Commit the edits!
        editor.commit();
    }

    public static String getDateString(String wStart) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        DateFormat df = DateFormat.getDateTimeInstance();
        try {
            return df.format(sdf.parse(wStart));
        } catch (ParseException e) {
            Log.e("UTILITY", "THere was an exception while parsing the date time to human readable format", e.fillInStackTrace());
        }
        return wStart;
    }

    public static boolean shouldRunBackgroundService(Context context) {
        SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
        return !settings.getBoolean(PREFS_VARIABLE_BACKGROUND_SERVICE_RAN, false);
    }

    public static void setBackgroundServiceRan(Context context) {
        SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putBoolean(PREFS_VARIABLE_BACKGROUND_SERVICE_RAN, true);

        // Commit the edits!
        editor.commit();

    }

    public static void getQuantity(Context context, String part, String location, TextView quantity) {
        DatabaseHandler db = new DatabaseHandler(context);
        quantity.setText(String.valueOf(db.getQuantity(part, location)));
    }

    public static void initDB(Context context) {
        SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
        if (!settings.getBoolean(PREFS_VARIABLE_INITIALIZE_DB, false)) {
            DatabaseHandler db = new DatabaseHandler(context);
            db.init(context);
            SharedPreferences.Editor editor = settings.edit();
            editor.putBoolean(PREFS_VARIABLE_INITIALIZE_DB, true);
            // Commit the edits!
            editor.commit();
        }
    }

    public static List<FEReport> getFeReportsToBeSubmitted(Context context) {
        DatabaseHandler db = new DatabaseHandler(context);
        return db.getAllFEReportsPending(context);
    }

    public static String postFeReport(Context context, FEReport feReport) {
        BufferedReader in = null;
        String myurl = Utility.POST_FE_REPORT_URL;
        InputStream is = null;
        try {
            Log.d(DEBUG_TAG, "Sending 'GET' request to URL :" + myurl);
            //here you use the WsseToken class to get wsse headers
            WsseToken token = new WsseToken(getUserName(context), getUserPassword(context), getUserSalt(context));
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
//            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            String param = getQuery(feReport.createNameValuePairs(context));
            conn.setFixedLengthStreamingMode(param.getBytes().length);
            conn.setRequestProperty("Content-Length", String.valueOf(param.getBytes().length));
            conn.setConnectTimeout(15000);
            conn.setReadTimeout(15000);
            conn.setRequestProperty(WsseToken.HEADER_AUTHORIZATION, token.getAuthorizationHeader());
            conn.setRequestProperty(WsseToken.HEADER_WSSE, token.getWsseHeader());
            conn.setRequestProperty("User-Agent", USER_AGENT);
            conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
            conn.setRequestProperty("Content-Language", "en-US");
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(param);
            writer.flush();
            writer.close();
            os.close();

            conn.connect();
            int response = conn.getResponseCode();
            Log.d(DEBUG_TAG, "Sending 'POST' request to URL :" + myurl);
            Log.d(DEBUG_TAG, "The response is: " + response);
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            // Convert the InputStream into a string
            return readResponse(in);
            // Makes sure that the InputStream is closed after the app is
            // finished using it.
        } catch (MalformedURLException e) {
            Log.e(TAG, "Could not submit the fe report due to the MalformedURLException exception", e.fillInStackTrace());
        } catch (UnsupportedEncodingException e) {
            Log.e(TAG, "Could not submit the fe report due to the UnsupportedEncodingException exception", e.fillInStackTrace());
        } catch (ProtocolException e) {
            Log.e(TAG, "Could not submit the fe report due to the ProtocolException exception", e.fillInStackTrace());
        } catch (IOException e) {
            Log.e(TAG, "Could not submit the fe report due to the IOException exception", e.fillInStackTrace());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    Log.e(TAG, "Could not close the Input Stream due to the IOException exception", e.fillInStackTrace());
                }
            }
        }
        return null;
    }

    private static String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for (NameValuePair pair : params) {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(pair.getName());
//            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        }
        Log.i(TAG, "The Query parameters are as follows:" + result.toString());
        return result.toString();
    }

    public static String getPart(Context context, String part_name) {
        DatabaseHandler db = new DatabaseHandler(context);
        Part part = db.getPartByName(part_name);
        if (part != null) {
            return String.valueOf(part.getPartId());
        } else {
            return "0";
        }
    }

    public static String getLocation(Context context, String location_name) {
        DatabaseHandler db = new DatabaseHandler(context);
        Location location = db.getLocationByName(location_name);
        if (location != null) {
            return String.valueOf(location.getLocationId());
        } else {
            return "0";
        }
    }

    // Uses AsyncTask to create a task away from the main UI thread. This task takes a
    // URL string and uses it to create an HttpUrlConnection. Once the connection
    // has been established, the AsyncTask downloads the contents of the webpage as
    // an InputStream. Finally, the InputStream is converted into a string, which is
    // displayed in the UI by the AsyncTask's onPostExecute method.
    private static class DownloadWebpageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... str) {
            // params comes from the execute() call: params[0] is the url.
            try {
                return downloadUrl(getURL(Integer.valueOf(str[0])), getPostParams(Integer.valueOf(str[0])));
            } catch (IOException e) {
                Log.e(DEBUG_TAG, "Unable to retrieve due to network connection not available. " +
                        "Please check your Network Connection.");
                return null;
            }
        }

        protected void onPostExecute(String response) {
            Log.e(DEBUG_TAG, "Downloaded response: " + response);
        }
    }
}
